<template>
    <div class="maintenance-container">
        <!-- 搜索表单 -->
        <div class="search-form">
            <el-form :inline="true" :model="searchForm">
                <el-form-item label="条形码">
                    <el-input v-model="searchForm.BarCode" placeholder="请输入条形码"></el-input>
                </el-form-item>
                <el-form-item label="BOM编号">
                    <el-input v-model="searchForm.BomCode" placeholder="请输入BOM编号"></el-input>
                </el-form-item>
                <el-form-item label="产品编码">
                    <el-input v-model="searchForm.ProductCode" placeholder="请输入产品编码"></el-input>
                </el-form-item>
                <el-form-item label="订单编码">
                    <el-input v-model="searchForm.OrderCode" placeholder="请输入订单编码"></el-input>
                </el-form-item>
                <el-form-item label="创建时间">
                    <el-date-picker v-model="searchForm.TimeRange" type="daterange" range-separator="至"
                        start-placeholder="开始日期" end-placeholder="结束日期" value-format="YYYY-MM-DD"
                        @change="handleTimeRangeChange">
                    </el-date-picker>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleSearch">查询</el-button>
                    <el-button @click="resetSearch">重置</el-button>
                </el-form-item>
            </el-form>
        </div>

        <!-- 顶部操作按钮 -->
        <div class="toolbar">
            <!-- 在 toolbar 区域添加列显示控制按钮 -->
            <el-dropdown trigger="click">
                <el-button type="primary">
                    显示列设置 <i class="el-icon-arrow-down"></i>
                </el-button>
                <template #dropdown>
                    <el-dropdown-menu>
                        <el-dropdown-item>
                            <el-checkbox v-model="columnDisplay.barCode" @change="saveColumnSettings">条形码</el-checkbox>
                        </el-dropdown-item>
                        <el-dropdown-item>
                            <el-checkbox v-model="columnDisplay.productCode" @change="saveColumnSettings">产品编码</el-checkbox>
                        </el-dropdown-item>
                        <el-dropdown-item>
                            <el-checkbox v-model="columnDisplay.productNum" @change="saveColumnSettings">产品数量</el-checkbox>
                        </el-dropdown-item>
                        <el-dropdown-item>
                            <el-checkbox v-model="columnDisplay.productDesc" @change="saveColumnSettings">产品描述</el-checkbox>
                        </el-dropdown-item>
                        <el-dropdown-item>
                            <el-checkbox v-model="columnDisplay.bomCode" @change="saveColumnSettings">BOM编码</el-checkbox>
                        </el-dropdown-item>
                        <el-dropdown-item>
                            <el-checkbox v-model="columnDisplay.batch" @change="saveColumnSettings">批次</el-checkbox>
                        </el-dropdown-item>
                        <el-dropdown-item>
                            <el-checkbox v-model="columnDisplay.orderCode" @change="saveColumnSettings">订单编码</el-checkbox>
                        </el-dropdown-item>
                        <el-dropdown-item>
                            <el-checkbox v-model="columnDisplay.road" @change="saveColumnSettings">工艺路线</el-checkbox>
                        </el-dropdown-item>
                        <el-dropdown-item>
                            <el-checkbox v-model="columnDisplay.productSize" @change="saveColumnSettings">产品规格</el-checkbox>
                        </el-dropdown-item>
                        <el-dropdown-item>
                            <el-checkbox v-model="columnDisplay.quality" @change="saveColumnSettings">品质</el-checkbox>
                        </el-dropdown-item>
                        <el-dropdown-item>
                            <el-checkbox v-model="columnDisplay.question" @change="saveColumnSettings">问题工位</el-checkbox>
                        </el-dropdown-item>
                        <el-dropdown-item>
                            <el-checkbox v-model="columnDisplay.createTime" @change="saveColumnSettings">创建时间</el-checkbox>
                        </el-dropdown-item>
                    </el-dropdown-menu>
                </template>
            </el-dropdown>
            <el-button type="danger" @click="batchDelete" :disabled="!selectedRows.length" style="margin-left: 10px;">
                <i class="el-icon-delete"></i> 批量删除
            </el-button>
            <el-button type="primary" @click="handleAdd">
                <i class="el-icon-plus"></i> 添加
            </el-button>
        </div>

        <!-- 数据表格 -->
        <el-table :data="tableData" @selection-change="handleSelectionChange" border style="width: 100%">
            <el-table-column type="selection" width="55">
            </el-table-column>
            <el-table-column prop="id" label="ID" width="80"></el-table-column>
            <el-table-column v-if="columnDisplay.barCode" prop="barCode" label="条形码" width="150"></el-table-column>
            <el-table-column v-if="columnDisplay.productCode" prop="productCode" label="产品编码" width="150"></el-table-column>
            <el-table-column v-if="columnDisplay.productNum" prop="productNum" label="产品数量" width="100"></el-table-column>
            <el-table-column v-if="columnDisplay.productDesc" prop="productDesc" label="产品描述" width="150"></el-table-column>
            <el-table-column v-if="columnDisplay.bomCode" prop="bomCode" label="BOM编码" width="120"></el-table-column>
            <el-table-column v-if="columnDisplay.batch" prop="batch" label="批次" width="100"></el-table-column>
            <el-table-column v-if="columnDisplay.orderCode" prop="orderCode" label="订单编码" width="150"></el-table-column>
            <el-table-column v-if="columnDisplay.road" prop="road" label="工艺路线" width="120"></el-table-column>
            <el-table-column v-if="columnDisplay.productSize" prop="productSize" label="产品规格" width="120"></el-table-column>
            <el-table-column v-if="columnDisplay.quality" prop="quality" label="品质" width="100"></el-table-column>
            <el-table-column v-if="columnDisplay.question" prop="question" label="问题工位" width="150"></el-table-column>
            <el-table-column v-if="columnDisplay.createTime" prop="createTime" label="创建时间" width="160"></el-table-column>
            <el-table-column label="操作" fixed="right" width="150">
                <template #default="scope">
                    <el-button type="primary" size="small" @click="handleEdit(scope.row)">
                        编辑
                    </el-button>
                    <el-button type="danger" size="small" @click="handleDelete(scope.row)">
                        删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
            :current-page="searchForm.PageIndex" :page-sizes="[10, 20, 50, 100]" :page-size="searchForm.PageSize"
            layout="total, sizes, prev, pager, next, jumper" :total="searchForm.TotalCount">
        </el-pagination>

        <!-- 添加记录的对话框 -->
        <el-dialog title="添加维护记录" v-model="dialogFormVisible" width="50%" :close-on-click-modal="false">
            <el-form :model="addForm" :rules="rules" ref="addFormRef" label-width="100px" style="margin: 40px;">
                <el-form-item label="条形码" prop="barCode">
                    <el-input v-model="addForm.barCode" placeholder="请输入条形码"></el-input>
                </el-form-item>
                <el-form-item label="产品编码" prop="productCode">
                    <el-input v-model="addForm.productCode" placeholder="请输入产品编码"></el-input>
                </el-form-item>
                <el-form-item label="产品数量" prop="productNum">
                    <el-input v-model="addForm.productNum" placeholder="请输入产品数量"></el-input>
                </el-form-item>
                <el-form-item label="产品描述" prop="productDesc">
                    <el-input v-model="addForm.productDesc" placeholder="请输入产品描述"></el-input>
                </el-form-item>
                <el-form-item label="BOM编码" prop="bomCode">
                    <el-select v-model="addForm.bomCode" placeholder="请选择BOM编码" style="width: 100%">
                        <el-option
                            v-for="item in bomList"
                            :label="item.bomCode"
                            :value="item.bomCode">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="批次" prop="batch">
                    <el-input v-model="addForm.batch" placeholder="请输入批次"></el-input>
                </el-form-item>
                <el-form-item label="订单编码" prop="orderCode">
                    <el-input v-model="addForm.orderCode" placeholder="请输入订单编码"></el-input>
                </el-form-item>
                <el-form-item label="工艺路线" prop="road">
                    <el-select v-model="addForm.road" placeholder="请选择工艺路线">
                        <el-option label="路线1" value="路线1"></el-option>
                        <el-option label="路线2" value="路线2"></el-option>
                        <el-option label="路线3" value="路线3"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="产品规格" prop="productSize">
                    <el-input v-model="addForm.productSize" placeholder="请输入产品规格"></el-input>
                </el-form-item>
                <el-form-item label="品质" prop="quality">
                    <el-input v-model="addForm.quality" placeholder="请输入品质"></el-input>
                </el-form-item>
                <el-form-item label="问题工位" prop="question">
                    <el-input v-model="addForm.question" placeholder="请输入问题工位"></el-input>
                </el-form-item>
                <el-form-item label="生产日期" prop="createTime">
                    <el-date-picker v-model="addForm.createTime" type="datetime" placeholder="选择日期时间"
                        value-format="YYYY-MM-DD HH:mm:ss"></el-date-picker>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogFormVisible = false">取消</el-button>
                    <el-button type="primary" @click="submitAdd">确定</el-button>
                </span>
            </template>
        </el-dialog>

        <!-- 编辑对话框 -->
        <el-dialog title="编辑维护记录" v-model="editDialogVisible" width="50%" :close-on-click-modal="false">
            <el-form :model="editForm" :rules="rules" ref="editFormRef" label-width="100px" style="margin: 40px;">
                <el-form-item label="条形码" prop="barCode">
                    <el-input v-model="editForm.barCode" placeholder="请输入条形码"></el-input>
                </el-form-item>
                <el-form-item label="产品编码" prop="productCode">
                    <el-input v-model="editForm.productCode" placeholder="请输入产品编码"></el-input>
                </el-form-item>
                <el-form-item label="产品数量" prop="productNum">
                    <el-input v-model="editForm.productNum" placeholder="请输入产品数量"></el-input>
                </el-form-item>
                <el-form-item label="产品描述" prop="productDesc">
                    <el-input v-model="editForm.productDesc" placeholder="请输入产品描述"></el-input>
                </el-form-item>
                <el-form-item label="BOM编码" prop="bomCode">
                    <el-select v-model="editForm.bomCode" placeholder="请选择BOM编码" style="width: 100%">
                        <el-option
                            v-for="item in bomList"
                            :label="item.bomCode"
                            :value="item.bomCode">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="批次" prop="batch">
                    <el-input v-model="editForm.batch" placeholder="请输入批次"></el-input>
                </el-form-item>
                <el-form-item label="订单编码" prop="orderCode">
                    <el-input v-model="editForm.orderCode" placeholder="请输入订单编码"></el-input>
                </el-form-item>
                <el-form-item label="工艺路线" prop="road">
                    <el-select v-model="editForm.road" placeholder="请选择工艺路线">
                        <el-option label="路线1" value="路线1"></el-option>
                        <el-option label="路线2" value="路线2"></el-option>
                        <el-option label="路线3" value="路线3"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="产品规格" prop="productSize">
                    <el-input v-model="editForm.productSize" placeholder="请输入产品规格"></el-input>
                </el-form-item>
                <el-form-item label="品质" prop="quality">
                    <el-input v-model="editForm.quality" placeholder="请输入品质"></el-input>
                </el-form-item>
                <el-form-item label="问题工位" prop="question">
                    <el-input v-model="editForm.question" placeholder="请输入问题工位" type="number"></el-input>
                </el-form-item>
                <el-form-item label="生产日期" prop="createTime">
                    <el-date-picker v-model="editForm.createTime" type="datetime" placeholder="选择日期时间"
                        value-format="YYYY-MM-DD HH:mm:ss"></el-date-picker>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="editDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="submitEdit">确定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">

import http from '@/api/http'; // 假设有一个http模块用于API请求
import { ElMessageBox, ElMessage } from 'element-plus'; // 引入Element Plus的消息提示组件
import { onMounted, reactive, ref, nextTick } from 'vue'; // 引入Vue的生命周期钩子
import { getCurrentInstance } from 'vue'
onMounted(() => {
    loadData();
    getBomList() // 获取BOM列表
})

const tableData: any = ref([])
const selectedRows: any = ref([])
const searchForm: any = reactive({
    BarCode: '', // 条形码
    BomCode: '', // BOM编号
    ProductCode: '', // 产品编码
    OrderCode: '', // 订单编码
    TimeRange: [], // 时间范围
    StartTime: '', // 开始时间
    EndTime: '', // 结束时间
    PageIndex: 1, // 当前页码
    PageSize: 10, // 每页数量
    TotalCount: 0 // 总条数
})

// 添加表单数据
const addForm = reactive({
    id: 0,
    barCode: '',
    productCode: '',
    productNum: '',
    productDesc: '',
    bomCode: '',
    batch: '',
    orderCode: '',
    road: '',
    productSize: '',
    quality: '',
    question: '',
    createTime: ''
})

// 添加编辑表单数据对象
const editForm = reactive({
    id: 0,
    barCode: '',
    productCode: '',
    productNum: '',
    productDesc: '',
    bomCode: '',
    batch: '',
    orderCode: '',
    road: '',
    productSize: '',
    quality: '',
    question: '',
    createTime: ''
})

// 控制对话框显示
const dialogFormVisible = ref(false)
// 控制编辑对话框显示
const editDialogVisible = ref(false)

// 表单验证规则
const rules = reactive({
    barCode: [{ required: true, message: '请输入条形码', trigger: 'blur' }],
    productCode: [{ required: true, message: '请输入产品编码', trigger: 'blur' }],
    productNum: [{ required: true, message: '请输入产品数量', trigger: 'blur' }],
    productDesc: [{ required: true, message: '请输入产品描述', trigger: 'blur' }],
    bomCode: [{ required: true, message: '请输入BOM编码', trigger: 'blur' }],
    batch: [{ required: true, message: '请输入批次', trigger: 'blur' }],
    orderCode: [{ required: true, message: '请输入订单编码', trigger: 'blur' }],
    road: [{ required: true, message: '请选择工艺路线', trigger: 'change' }],
    productSize: [{ required: true, message: '请输入产品规格', trigger: 'blur' }],
    quality: [{ required: true, message: '请输入品质', trigger: 'blur' }],
    question: [
        { required: true, message: '请输入问题工位', trigger: 'blur' },
        {
            pattern: /^[0-9]*$/,
            message: '问题工位只能输入数字',
            trigger: ['blur', 'change']
        }
    ]
})

// 表单引用
const addFormRef = ref()
const editFormRef = ref()

// 处理多选变化
const handleSelectionChange: any = (val: any) => {
    selectedRows.value = val;
}
// 批量删除
const batchDelete: any = () => {
    const ids = selectedRows.value.map((row: any) => row.id);
    if (!ids.length) {
        ElMessage.warning('请选择要删除的记录');
        return;
    }
    ElMessageBox.confirm('确认删除选中的记录?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }
    )
        .then(() => {
            http.post('/api/Maintenance/DelMaintenance', ids.toString());
            ElMessage.success('删除成功');
            window.location.reload(); // 重新加载页面

        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '删除取消',
            })
        })
}

// 添加记录
const handleAdd = async () => {
    await getBomList() // 获取最新的BOM列表
    dialogFormVisible.value = true
    // 重置表单数据，并设置默认条形码
    Object.assign(addForm, {
        barCode: generateBarCode(), // 生成默认条形码
        productCode: '',
        productNum: '',
        productDesc: '',
        bomCode: '',
        batch: '',
        orderCode: '',
        road: '',
        productSize: '',
        quality: '',
        question: '',
        createTime: ''
    })
    // 重置表单验证结果
    nextTick(() => {
        addFormRef.value?.resetFields()
    })
}

// 提交添加
const submitAdd = async () => {
    try {
        // 表单验证
        await addFormRef.value.validate()

        // 验证通过后提交
        await http.post('/api/Maintenance/AddMaintenance', addForm)
        ElMessage.success('添加成功')
        dialogFormVisible.value = false
        loadData() // 重新加载数据
    } catch (error) {
        if (error === false) {
            // 表单验证失败
            ElMessage.warning('请完善必填项')
        } else {
            // 提交失败
            console.error('添加失败:', error)
            ElMessage.error('添加失败')
        }
    }
}

// 获取BOM列表
const bomList:any = ref([])

const getBomList = async () => {
    try {
        const res = await http.get(`/api/MaterialManagement/GetBom?PageSize=${100}`)
        bomList.value = res.data.items
       
    } catch (error) {
        console.error('获取BOM列表失败:', error)
        ElMessage.error('获取BOM列表失败')
    }
}

// 编辑记录
const handleEdit = async (row: any) => {
    await getBomList() // 获取最新的BOM列表
    editDialogVisible.value = true
    try {
        // 获取详细数据
        http.get(`/api/Maintenance/GetMaintenanceById?maintenanceId=${row.id}`)
            .then(res => {
                Object.assign(editForm, res.data)
                console.log('编辑数据:', editForm)
            })
    } catch (error) {
        console.error('获取详情失败:', error)
        ElMessage.error('获取详情失败')
    }
}

// 提交编辑
const submitEdit = () => {
    try {
        // 表单验证
        editFormRef.value.validate()

        // 提交更新
        http.post('/api/Maintenance/UpdateMaintenance', editForm)
        ElMessage.success('更新成功')
        editDialogVisible.value = false
        loadData() // 重新加载表格数据
    } catch (error) {
        if (error === false) {
            // 表单验证失败
            ElMessage.warning('请完善必填项')
        } else {
            // 提交失败
            console.error('更新失败:', error)
            ElMessage.error('更新失败')
        }
    }
}

// 删除单条记录
const handleDelete: any = (row: any) => {
    console.log(row)
    ElMessageBox.confirm('确认删除该记录?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }
    )
        .then(() => {
            http.post('/api/Maintenance/DelMaintenance', row.id);
            ElMessage.success('删除成功');
            loadData(); // 重新加载数据
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '删除取消',
            })
        })
}

// 加载表格数据
const loadData: any = () => {
    http.get(`/api/Maintenance/GetAllMaintenance?BarCode=${searchForm.BarCode}&BomCode=${searchForm.BomCode}&ProductCode=${searchForm.ProductCode}&OrderCode=${searchForm.OrderCode}&StartTime=${searchForm.StartTime}&EndTime=${searchForm.EndTime}&PageIndex=${searchForm.PageIndex}&PageSize=${searchForm.PageSize}`)
        .then((res: any) => {
            tableData.value = res.data.items; // 假设返回的数据在Data字段中
            searchForm.TotalCount = res.data.totalCount; // 假设总条数在TotalCount字段中
        });
}
// 处理页码变化
const handleCurrentChange = (currentPage: any) => {
    searchForm.PageIndex = currentPage;
    loadData();
}

// 处理每页条数变化
const handleSizeChange = (size: any) => {
    searchForm.PageSize = size;
    loadData();
}

// 查询
const handleSearch = () => {
    searchForm.PageIndex = 1; // 搜索时重置为第一页
    loadData();
}

// 重置搜索
const resetSearch = () => {
    // 使用 Object.assign 重置 reactive 对象
    Object.assign(searchForm, {
        BarCode: '',
        BomCode: '',
        ProductCode: '',
        OrderCode: '',
        TimeRange: [],
        StartTime: '',
        EndTime: '',
        PageIndex: 1,
        PageSize: 10,
        TotalCount: 0
    });

    // 重新加载数据
    loadData();

    // 提示用户重置成功
    ElMessage({
        type: 'success',
        message: '重置成功'
    });
}

// 处理时间范围变化
const handleTimeRangeChange = (val: any) => {
    if (val) {
        searchForm.StartTime = val[0];
        searchForm.EndTime = val[1];
    } else {
        searchForm.StartTime = '';
        searchForm.EndTime = '';
    }
}

// 在 script setup 中添加生成随机条形码的函数
const generateBarCode = () => {
    // 生成9位随机数
    const randomNum = Math.floor(Math.random() * 1000000000).toString().padStart(9, '0');
    return `PCB${randomNum}`;
}

// 列显示控制
const columnDisplay = reactive({
    barCode: true,
    productCode: true,
    productNum: true,
    productDesc: true,
    bomCode: true,
    batch: true,
    orderCode: true,
    road: true,
    productSize: true,
    quality: true,
    question: true,
    createTime: true
})

// 保存列显示设置
const saveColumnSettings = () => {
    localStorage.setItem('maintenanceColumnSettings', JSON.stringify(columnDisplay))
}

// 从 localStorage 加载列显示设置
const loadColumnSettings = () => {
    const settings = localStorage.getItem('maintenanceColumnSettings')
    if (settings) {
        Object.assign(columnDisplay, JSON.parse(settings))
    }
}

// 在组件挂载时加载设置
onMounted(() => {
    loadColumnSettings()
    loadData()
    getBomList()
})

</script>

<style scoped>
.maintenance-container {
    padding: 20px;
}

.toolbar {
    margin-bottom: 20px;
}

.pagination {
    margin-top: 20px;
    text-align: right;
}
</style>